package com.service;

import com.entity.VehicleDailyMileage;
import com.repository.VehicleDailyMileageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class VehicleDailyMileageService {

    @Autowired
    private VehicleDailyMileageRepository vehicleDailyMileageRepository;

    /**
     * 保存里程记录
     *
     * @param vehicleDailyMileage 里程记录
     * @return 保存后的对象
     */
    public VehicleDailyMileage save(VehicleDailyMileage vehicleDailyMileage) {
        if (vehicleDailyMileage.getId() == null) {
            vehicleDailyMileage.setCreateTime(new Date());
        }
        vehicleDailyMileage.setUpdateTime(new Date());
        return vehicleDailyMileageRepository.save(vehicleDailyMileage);
    }

    /**
     * 根据ID删除里程记录
     *
     * @param id ID
     */
    public void deleteById(Integer id) {
        vehicleDailyMileageRepository.deleteById(id);
    }

    /**
     * 根据ID获取里程记录
     *
     * @param id ID
     * @return 里程记录
     */
    @Transactional(readOnly = true)
    public Optional<VehicleDailyMileage> findById(Integer id) {
        return vehicleDailyMileageRepository.findById(id);
    }

    /**
     * 分页查询里程记录
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 里程记录分页数据
     */
    @Transactional(readOnly = true)
    public Page<VehicleDailyMileage> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return vehicleDailyMileageRepository.findAll(pageable);
    }

    /**
     * 根据车牌号查询里程记录
     *
     * @param plateNumber 车牌号
     * @param pageNum     页码
     * @param pageSize    每页数量
     * @return 里程记录分页数据
     */
    @Transactional(readOnly = true)
    public Page<VehicleDailyMileage> findByPlateNumberContaining(String plateNumber, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return vehicleDailyMileageRepository.findByPlateNumberContaining(plateNumber, pageable);
    }
}